export function getCurrentPage() {
    const pages = getCurrentPages()
    return pages[pages.length - 1]
}

export function setTool(key, value) {
    const page = getCurrentPage()
    const tools = page.$tools || {}
    tools[key] = value
    page.$tools = tools
}

export function getTools() {
    const page = getCurrentPage()
    return page.$tools || {}
}


export function deepCopy(obj) {
    if (obj == null) {
        return null
    }
    if (typeof obj == 'string' || typeof obj == 'number' || typeof obj == 'boolean') {
        return obj
    }
    return JSON.parse(JSON.stringify(obj))
}

export function copyProperty(options) {
    const target = options.target
    
    if (target) {
        const source = options.source ?? {}
        
        const keys = Object.keys(source)
        
        keys.forEach(key => {
            target[key] = source[key]
        })
        
        Object.keys(target).forEach(key => {
            if (keys.includes(key)) {
                return
            }
            delete target[key]
        })
    }
}


export function defineEnum(obj, key = 'value') {
    
    const fn = value => {
        for (const item of Object.values(obj)) {
            if (item[key] === value) {
                return item
            }
        }
    }
    
    Object.assign(fn, obj)
    
    return fn
}


const refCache = {}

export function globalRef(key) {
    if (refCache[key]) {
        return refCache[key]
    }
    refCache[key] = ref()
    return refCache[key]
}

export function componentEvent(key, callback) {
    onMounted(() => {
        uni.$on(key, callback)
    })
    
    onBeforeUnmount(() => {
        uni.$off(key, callback)
    })
}


export function rpxToPx(rpx) {
    const screenWidth = uni.getSystemInfoSync().screenWidth
    return (screenWidth * Number.parseInt(rpx)) / 750
}

export function pxToRpx(px) {
    const screenWidth = uni.getSystemInfoSync().screenWidth
    return (750 * Number.parseInt(px)) / screenWidth
}
